package com.kly.test.function.like

import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.kly.test.base.BaseVMFragment
import com.kly.test.base.adpater.isRefreshing
import androidx.lifecycle.Observer
import com.kly.test.databinding.FragmentWlmBinding
import com.kly.test.function.like.adapter.LikeDataListAdapter
import com.kly.test.function.like.viewmodel.ItemType
import com.kly.test.function.like.viewmodel.WhoLikeMeViewModel
import com.kly.test.function.like.viewmodel.WhoLikeMeViewModelFactory

class LikeListFragment: BaseVMFragment<FragmentWlmBinding, WhoLikeMeViewModel>(
    FragmentWlmBinding::inflate,
    WhoLikeMeViewModel::class.java
) {

    private val viewModelFactory by lazy { WhoLikeMeViewModelFactory() } // 可以@Inject
    private val viewModel: WhoLikeMeViewModel by viewModels { viewModelFactory }
    private val adapter by lazy { LikeDataListAdapter() }
    override fun initData() {
        initialViews()
        dispatchRequest()
        viewModel.dataAllList.observe(this, Observer {
            adapter.submitList(it)
        })

        viewModel.loading.observe(this, Observer {
            binding?.refreshLayout?.isRefreshing = it.isRefreshing()
        })
    }


    override fun initListener() {

    }

    private fun dispatchRequest() {
        viewModel.reqIndexList(true)
    }

    override fun onDestroyView() {
        binding?.recyclerView?.adapter = null
        adapter.setListener(null)
        binding?.refreshLayout?.setOnRefreshListener(null)
        super.onDestroyView()
    }

    private fun initialViews() {
        binding?.refreshLayout?.setOnRefreshListener {
            dispatchRequest()
        }
        binding?.recyclerView?.layoutManager = GridLayoutManager(context, 2).apply { spanSizeLookup = PopularLayoutManagerSpanSizeLookUp(adapter) }
        binding?.recyclerView?.itemAnimator = null
        binding?.recyclerView?.adapter = adapter
    }

}

private class PopularLayoutManagerSpanSizeLookUp(val adapter: LikeDataListAdapter) : GridLayoutManager.SpanSizeLookup() {
    override fun getSpanSize(position: Int): Int {
        return when (adapter.getItemViewType(position)) {
            ItemType.LikeListData -> 1
            else -> 2
        }
    }
}